package com.cuoyi.coupon.mall.config;

import com.cuoyi.coupon.mall.interceptor.LoginInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author chengzhang
 * 2021/11/11 20:12
 */
@Slf4j
@Configuration
public class WebAppConfigurer implements WebMvcConfigurer {

    @Resource
    private LoginInterceptor loginInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor).addPathPatterns("/**").excludePathPatterns(getExcludePath());
    }

    private List<String> getExcludePath() {
        List<String> list = new ArrayList<>();
        //swagger-ui
        list.add("/v2/**");
        list.add("/v3/**");
        list.add("/swagger-ui.html");
        list.add("/swagger-resources");
        list.add("/swagger-resources/**");
        list.add("/webjars/**");
        list.add("/doc.html");

        list.add("/admin/login");
        list.add("/admin/image/**");
        list.add("/admin/dictionary/**");
        list.add("/admin/user/**");
        list.add("/app/**");
        return list;
    }


    /**
     * 配置跨域请求
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                //设置允许跨域请求的域名
                .allowedOriginPatterns("*")
                // 设置允许请求方式
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD")
                // 是否允许证书（cookies）
                .allowCredentials(true)
                // 预请求的结果能被缓存多久
                .maxAge(3600)
                // 设置允许的请求头
                .allowedHeaders("*");
    }
}
